package com.niiwoo.civet.user.service.duboo;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.system.dto.common.SysConfParamDTO;
import com.niiwoo.civet.system.service.SysParamService;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;

/**
 * 登录账户相关配置
 *
 * key=project:module:key:scope
 */
public interface UserSystemConfigurable {

    // 密码错误N次锁定账号
    String MAX_PASSWORD_ERROR_TIMES = "civet-user:loginAccount:maxPasswordErrorTimes:global";

    // 密码错误N次需要短信验证码
    String NEED_SMS_PASSWORD_ERROR_TIMES = "civet-user:loginAccount:needSMSPasswordErrorTimes:global";

    // 密码错误次数锁定账号持续时间, 单位小时
    String PASSWORD_ERROR_LOCK_DURATION = "civet-user:loginAccount:passwordErrorLockDuration:global";

    // 短息配置
    String SMS_CONFIGURATION = "civet-user:sms:configuration:global";

    /**
     * 获取配置并转换成指定 List
     */
    default <T> Optional<List<T>> getSysConfList(String key, Class<T> exceptClass) {
        return getSysConfParamDto(key).map(sysConfParamDto -> JSON.parseArray(sysConfParamDto.getParamValue(), exceptClass));
    }

    /**
     * 获取配置并转换成指定 class
     */
    default <T> Optional<T> getSysConfBean(String key, Class<T> exceptClass) {
        return getSysConfParamDto(key).map(sysConfParamDto -> JSON.parseObject(sysConfParamDto.getParamValue(), exceptClass));
    }

    /**
     * 获取配置
     */
    default Optional<SysConfParamDTO> getSysConfParamDto(String key) {
        return StringUtils.isBlank(key) ? Optional.empty() : Optional.ofNullable(getSysParamService().queryParamByKey(key));
    }

    SysParamService getSysParamService();

}
